# -*- coding: utf-8 -*-

"""
Created on Fri Jun  8 18:43:24 2018

@author: Administrator
"""
print('shell_script-shell_script-shell_script')
import os
import subprocess

#%%

class Basic_str(object):
  
    ############################################################################basic strings
    underline = '_'
    linkline = '-'
    os_sep = os.sep
    cmd_sep = ' && '
    space = ' '
    star = '*'
    left_bracket = '['
    right_bracket = ']'
    quation = '"'
    s_quation = "'"
    semicolon = ';'
    comma = ','
    left_brace_quation = "{'"
    right_brace_quation = "'}"
    l_brace_quation = "{"
    r_brace_quation = "}"
    equal_mark = r'=' 
    newline_mark = ' \n '
    
    subj_str = 'subj'
    
#    modality = '_BOLD'   #this can be '_PET'  '_CBF'  '_ASL'  貌似没有用了
    suffix = '.nii'
    star_suffix = '*.nii*'
    suffix_gz = '.nii.gz'
    T1_str = '*T1*'
    mat_str = r'.mat'
    png_str = r'.png'
    condition = 'error'   #用于判断返回stdout_err的。
    txt_str = '.txt'
    fts_str = '.fts'
    con_str = 'con'

#%%
class Shell_script(Basic_str):
    #作用原理：
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：

    def __init__(self,input_list=[]):
        self.initialize_input_list(input_list)
        self.concat_inputs()
        self.concat_script()
        self.excute_shell_script()
    
    def initialize_input_list(self,input_list):
        pass
    def concat_inputs(self):
        pass
    def concat_script(self):
        ###########################################################################构造命令、即脚本执行。
        pass
        
    def excute_shell_script(self):
        print(self.shell_script)
        popen_subj = subprocess.Popen(self.shell_script,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        stdout_err = popen_subj.communicate()
        ############################################################################命令运行信息处理
        #因为3dcalc无论执行成功与否，其标准输出都在stderr里面，导致stdout_err[0]恒为b'',而stdout_err[1]恒存在，故此处通过stdout_err[1]中是否含有b'error'来判断，
        #但不知这种方式是否会有漏洞。因为无论执行是否成功，returncode恒等于0，所以也无法通过这种方式来判断。
        if self.condition in stdout_err[1].decode().lower():
            self.stdout_err = stdout_err
#            print('in the excute_shell_script if  self.stdout_err :',self.stdout_err)
        else:
            stdout_err = None
            self.stdout_err = stdout_err
#            print('in the excute_shell_script else  self.stdout_err :',self.stdout_err)
#%%
class Matlab(object):
    matlab_cmd_str = r"matlab -nojvm -nodesktop -nodisplay  -nosplash -r "


#%%
class Spm(Matlab):
    spm_normalize_str = 'w'
    spm_reslice_str = 'r'
    spm_deformfield_str = 'y_'
    spm_smooth_str = 's'
    spm_jobman_initcfg = r"spm_jobman('initcfg');"
    spm_jobman_run = r"spm_jobman('run',jobs);exit;"